package cn.itzzx.lagou.mybatis.config;

import cn.itzzx.lagou.mybatis.pojo.Configuration;
import cn.itzzx.lagou.mybatis.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * TODO 写点注视啦
 *
 * @author Martin
 * @date 2020-04-25
 * @see 1.0
 */
public class XmlMappedBuilder {

    private Configuration configuration;

    public XmlMappedBuilder(Configuration configuration){
        this.configuration = configuration;
    }
    private String namespace;


    /**
     * 解析 mapper.xml 配置文件 <select/> <update/> <insert/> <delete/>
     * @param inputStream
     * @throws DocumentException
     */
    public void parseMapper(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        //获取namespace
        namespace = rootElement.attributeValue("namespace");
        //解析<select/>
        parseSelect(rootElement.selectNodes("//select"));
        //解析<insert/>
        parseSelect(rootElement.selectNodes("//insert"));
        //解析<update/>
        parseSelect(rootElement.selectNodes("//update"));
        //解析<delete/>
        parseSelect(rootElement.selectNodes("//delete"));
    }


    /**
     * 封装 MappedStatement 对象，依此装载到 cn.itzzx.lagou.mybatis.pojo.Configuration#mappedStatementMap
     * @param selectNodes
     */
    private void parseSelect(List<Element> selectNodes){
        for (Element selectNode : selectNodes) {
            String id = selectNode.attributeValue("id");
            String paramterType = selectNode.attributeValue("paramterType");
            String resultType = selectNode.attributeValue("resultType");
            String sql = selectNode.getText();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(paramterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            mappedStatement.setOperation(selectNode.getName());
            String key = namespace + "." +id;
            //装载 MappedStatement
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }
    }

}
